﻿<script lang="ts" setup name="warePlaceModel">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useWarePlaceModelApi } from '/@/api/interacting/warePlaceModel';
import { getUserList } from '/@/api/customer/userList';
import editDialog from '/@/views/interacting/warePlaceModel/component/editDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";

const warePlaceModelApi = useWarePlaceModelApi();
const router = useRouter();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const state = reactive({
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  userList: [] as any[], // 用户列表
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
});

// 页面加载时
onMounted(async () => {
  // 加载用户列表
  try {
    const res = await getUserList();
    console.log('用户列表API响应:', res);
    // 根据API响应结构，数据在result字段中
    let userList = res?.data?.result || res?.result || [];
    
    // 如果用户列表为空，尝试不同的数据结构
    if (userList.length === 0) {
      console.log('尝试其他数据结构...');
      userList = res?.data || res || [];
    }
    
    // 确保value是字符串格式，因为下拉框需要字符串值
    state.userList = userList.map((item: any) => ({
      ...item,
      value: String(item.value), // 确保value是字符串
      label: item.label
    }));
    
    console.log('用户列表数据:', state.userList);
    console.log('用户列表长度:', state.userList.length);
  } catch (_error) {
    console.error('加载用户列表失败:', _error);
  }
});

// 根据用户ID获取用户名称
const getUserName = (userId: any) => {
  if (!userId) return '';
  const user = state.userList.find(item => item.value == userId);
  return user ? user.label : userId;
};

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await warePlaceModelApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 删除
const delWarePlaceModel = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await warePlaceModelApi.delete({ id: row.id });
    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => { });
};

// 批量删除
const batchDelWarePlaceModel = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await warePlaceModelApi.batchDelete(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => { });
};

// 跳转到库位详情页面
const goToDetail = (row: any) => {
  router.push({
    path: `/interacting/warePlaceModel/detail/${row.id}`
  });
};

// 导出数据
const exportWarePlaceModelCommand = async (command: string) => {
  try {
    state.exportLoading = true;
    if (command === 'select') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map(u => u.id) });
      await warePlaceModelApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'current') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams);
      await warePlaceModelApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'all') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
      await warePlaceModelApi.exportData(params).then(res => downloadStreamFile(res));
    }
  } finally {
    state.exportLoading = false;
  }
}

handleQuery();
</script>
<template>
  <div class="warePlaceModel-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位编码">
              <el-input v-model="state.tableQueryParams.warePlaceCode" clearable placeholder="请输入库位编码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位名称">
              <el-input v-model="state.tableQueryParams.warePlaceName" clearable placeholder="请输入库位名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位容量">
              <el-input-number v-model="state.tableQueryParams.warePlaceVolume" clearable placeholder="请输入库位容量" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位主管">
              <el-select v-model="state.tableQueryParams.userId" clearable filterable placeholder="请选择库位主管">
                <el-option v-for="item in state.userList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位状态">
              <el-select clearable filterable v-model="state.tableQueryParams.warePlaceType" placeholder="请选择库位状态">
                <el-option value="true" label="是" />
                <el-option value="false" label="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="库位备注">
              <el-input v-model="state.tableQueryParams.warePlaceNote" clearable placeholder="请输入库位备注" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'warePlaceModel:page'"
                  v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true"
                  v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false"
                  v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDelWarePlaceModel"
                  :disabled="state.selectData.length == 0" v-auth="'warePlaceModel:batchDelete'"> 删除 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus"
                  @click="editDialogRef.openDialog(null, '新增库位表')" v-auth="'warePlaceModel:add'"> 新增 </el-button>
                <el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportWarePlaceModelCommand">
                  <el-button type="primary" style="margin-left:5px;" icon="ele-FolderOpened" v-reclick="20000"
                    v-auth="'warePlaceModel:export'"> 导出 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="select"
                        :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
                      <el-dropdown-item command="current">导出本页</el-dropdown-item>
                      <el-dropdown-item command="all">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy"
                  @click="importDataRef.openDialog()" v-auth="'warePlaceModel:import'"> 导入 </el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }"
        style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange"
        border>
        <el-table-column type="selection" width="40" align="center"
          v-if="auth('warePlaceModel:batchDelete') || auth('warePlaceModel:export')" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop='warePlaceCode' label='库位编码' show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" link @click="goToDetail(scope.row)">
              {{ scope.row.warePlaceCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop='warePlaceName' label='库位名称' show-overflow-tooltip />
        <el-table-column prop='warePlaceVolume' label='库位容量' show-overflow-tooltip />
        <el-table-column prop='userId' label='库位主管' show-overflow-tooltip>
          <template #default="scope">
            {{ getUserName(scope.row.userId) }}
          </template>
        </el-table-column>
        <el-table-column prop='warePlaceType' label='库位状态' show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.warePlaceType"> 是 </el-tag>
            <el-tag type="danger" v-else> 否 </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop='warePlaceNote' label='库位备注' show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip
          v-if="auth('warePlaceModel:update') || auth('warePlaceModel:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary"
              @click="editDialogRef.openDialog(scope.row, '编辑库位表')" v-auth="'warePlaceModel:update'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delWarePlaceModel(scope.row)"
              v-auth="'warePlaceModel:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
        @size-change="(val: any) => handleQuery({ pageSize: val })"
        @current-change="(val: any) => handleQuery({ page: val })" layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 200, 500]" :total="state.tableParams.total" size="small" background />
      <ImportData ref="importDataRef" :import="warePlaceModelApi.importData"
        :download="warePlaceModelApi.downloadTemplate" v-auth="'warePlaceModel:import'" @refresh="handleQuery" />
      <printDialog ref="printDialogRef" :title="'打印库位表'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
    </el-card>
  </div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>